package com.imooc.ajaxserver2;

import org.springframework.util.StringUtils;

import javax.servlet.*;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import java.io.IOException;

public class CrossFilter implements javax.servlet.Filter {
    @Override
    public void init(FilterConfig filterConfig) throws ServletException {

    }

    @Override
    public void doFilter(ServletRequest servletRequest, ServletResponse servletResponse, FilterChain filterChain) throws IOException, ServletException {
        HttpServletResponse response = (HttpServletResponse) servletResponse;
        // 用于简单跨域请求：
        /*response.addHeader("Access-Control-Allow-Origin", "http://127.0.0.1:8081");
        response.addHeader("Access-Control-Allow-Methods", "GET");*/

        // 用于非简单（@RequestBody contentTyep:application/json）跨域请求：*表示支持所有的跨域，但是带cookie是orign不能用*
        // response.addHeader("Access-Control-Allow-Origin", "*");
        response.addHeader("Access-Control-Allow-Methods", "*");
        // response.addHeader("Access-Control-Allow-Headers", "Content-Type");
        // 预检命令（浏览器上的非简单请求都会先发出一条预检命令，
        // 但有时这样会减缓我们的速度，所以给它一个缓存）缓存10s
        response.addHeader("Access-Control-Max-Age", "10");

        // 用于带cookie的跨域请求
        // 带cookie的跨域请求必须增加Credentials请求头，而且origin使用全匹配
        // response.addHeader("Access-Control-Allow-Origin", "http://127.0.0.1:8081");
        response.addHeader("Access-Control-Allow-Credentials", "true");

        // 解决cookie跨域origin只能一个固定的情况
        HttpServletRequest request = (HttpServletRequest) servletRequest;
        String origin = request.getHeader("Origin");
        if (origin != null && !"".equals(origin)) {
            response.addHeader("Access-Control-Allow-Origin", origin);
        }

        // 自定义请求头：支持所有表头
        String header = request.getHeader("Access-Control-Request-Headers");
        if (!StringUtils.isEmpty(header)) {
            response.addHeader("Access-Control-Allow-Headers", header);
        }

        filterChain.doFilter(servletRequest, servletResponse);
    }

    @Override
    public void destroy() {

    }
}
